<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/AppSaleOnline/libs/model.php");

class Invoice extends Model
{
    public function __construct()
    {
        parent::__construct();
    }

    // kiem tra su ton tai  cua mot hoa don trong CSDL
    public function check_exists_invoice($invoice_id)
    {
        $sql = "SELECT `invoice_id` FROM invoices ORDER BY `invoice_id` ASC";

        $result = mysqli_query($this->_link, $sql);

        // var_dump(mysqli_fetch_row($result)); exit();
        $invoice_id_list = array();

        // lay danh sach tat ca hoa don dua vao mang
        while($rows = mysqli_fetch_row($result))
        {
            $invoice_id_list[] = $rows;
        }
        // khoi tao mang list cac hoa don
        $list_invoice = array();

        for($i = 0; $i < sizeof($invoice_id_list); $i++)
        {
            array_push($list_invoice, $invoice_id_list[$i][0]); // day cac phan tu vao
        }

        $msg = "";
        if(in_array($invoice_id, $list_invoice))
        {
            $msg .= "Invoice exists!";
        } else {
            $msg .= "Valid invoice!";
        }
        return $msg;
    }

    // luu hoa don vao CSDL
    public function save_invoice_into_database($invoice_id, $user_name, $email, $address, $sum_total)
    {
        $sql = "INSERT INTO `invoices`(`invoice_id`, `user_name`, `email`, `address`, `sum_total`) VALUES('$invoice_id','$user_name', '$email', '$address', '$sum_total')";

        $result = mysqli_query($this->_link, $sql);

        $msg = "";
        if($result == null)
        {
            throw new Exception("Error ". mysqli_error($this->_link));
        }
        try { // neu ok thi vao try khong bi loi thi vao try
            $msg .= "Ok ban da luu hoa don thanh cong!";
        } catch(Exception $e)
        {
            $msg .= $e->getMessage();
        }
        return $msg;
    }

    // lay danh sach hoa don co trong csdl
    public function get_list_invoice()
    {
        $sql = "SELECT * FROM invoices ORDER BY `invoice_id` ASC";

        $result = mysqli_query($this->_link, $sql);

        if($result == null) {
            throw new Exception("Error ".mysqli_error($this->_link));
        }
        try {
            $data = array();
            while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $data[] = $rows;
            }
            return $data;
        } catch(Exception $e)
        {
            return $e->getMessage();
        }
    }
    
    // xoa mot hoa don 
    public function del_invoice_with_id($invoice_id)
    {
        $sql = "DELETE FROM invoices WHERE `invoice_id` = '$invoice_id'";
        
        // var_dump($sql); exit();
        
        $result = mysqli_query($this->_link, $sql);
        
        if($result == null) return false;
        return true;
    }
}